package classes
{
	import events.PropertyEvent;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	public class FileIOConnector extends EventDispatcher
	{
		private var connector:RemoteObject;
		private var properties:Properties;	
		private var currentDCOperation:String;
		private var eventManager:EventGateway;

		
		public function FileIOConnector()
		{
			properties = Properties.getInstance();
			connector = new RemoteObject();
			eventManager = EventGateway.getInstance();
			//eventManager.addEventListener(eventManager.registerPropertiesSetEvent(),propertiesLoaded);
			
			connector.destination = "ColdFusion";
			connector.source = 'flexfilemanager.cfc.tmt_file_io';
			connector.addEventListener(FaultEvent.FAULT,faultConnectionHandler);
		}
		
		private function propertiesLoaded(event:PropertyEvent):void{
			connector.source = properties.cfcHome+"tmt_file_io";			
		}	
		
		
		/*** FUNCTIONS CONNECTORS ***/
		public function getDirectoryList(directoryPath:String=null):void{
			if(directoryPath==null) directoryPath = properties.filemanagerRoot;
			connector.addEventListener(ResultEvent.RESULT,dirListingHandler);
			connector.getDirectoryList(directoryPath);
		}
	
		
		public function getFileList(directoryPath:String=null):void{
			if(directoryPath==null) directoryPath = properties.filemanagerRoot;
			connector.addEventListener(ResultEvent.RESULT,fileListingHandler);
			connector.getFileList(directoryPath);
		}
		
		public function deleteFile(filename:String):void{
			connector.addEventListener(ResultEvent.RESULT,fileDeleteHandler);
			connector.deleteFile(filename);
		}		
		
		
		
		/*** RETURN FUNCTIONS HANDLERS ***/
		private function dirListingHandler(event:ResultEvent):void{
			currentDCOperation = "Dir Listing";
			connector.removeEventListener(ResultEvent.RESULT,dirListingHandler);
			eventManager.dispatchListDirectoryEvent(event.result as ArrayCollection);
			trace("FileIOConnector - Directory Listing - Result ");
		}

		private function fileListingHandler(event:ResultEvent):void{
			currentDCOperation = "File Listing";
			eventManager.dispatchListFileEvent(event.result as ArrayCollection);
			connector.removeEventListener(ResultEvent.RESULT,fileListingHandler);
			trace("FileIOConnector - File Listing - Result ");
		}		

		private function fileDeleteHandler(event:ResultEvent):void{
			currentDCOperation = "Delete File";
			trace("FileIOConnector - File Deleted");
			connector.removeEventListener(ResultEvent.RESULT,fileDeleteHandler);
			eventManager.dispatchRefreshEvent();
		}
		
		private function faultConnectionHandler(event:FaultEvent):void{
				trace("FileIOConnector - "+currentDCOperation+" - Error\n"+event.message);			
		}
		

	}
}